<template>
  <div class="desktop-content" v-if="currentFoodData">
    <div class="desktop-column-box">
      <div class="pagingAndSearch-box">
        <div class="paging-list-box" v-if="oneCateList.length">
          <div
            class="paging-list-item"
            :class="{
              'paging-list-item-active':
                (oneCateList[pagingActiveIndex]?.id || null) === (cate.id || null)
            }"
            v-for="(cate, idx) in oneCateList"
            :key="cate.id || 'all'"
            @click="handleSelectOneCate(idx, cate)"
          >
            <div class="name">{{ cate.name }}</div>
          </div>
          <div class="paging-list-btn">
            <img
              class="left-btn"
              @click.stop="oneCatePreviousPage"
              src="@/assets/images/home/page-left-icon.png"
              :style="{ cursor: oneCategoryPage === 1 ? 'not-allowed' : 'pointer' }"
              alt=""
            />
            <img
              class="right-btn"
              @click.stop="oneCateNextPage"
              src="@/assets/images/home/page-right-icon.png"
              :style="{
                cursor: oneCategoryPage >= foodOneCategoryLastPage ? 'not-allowed' : 'pointer'
              }"
              alt=""
            />
          </div>
        </div>

        <div class="search-box">
          <div class="content1">
            <img src="@/assets/images/home/sousuo-icon.png" alt="" />
            <input
              v-model.trim="query.keywords"
              type="text"
              @input="onSearch"
              placeholder="搜索菜品配菜"
            />
          </div>
        </div>
      </div>

      <div class="tag-select-box" v-if="twoCateList.length">
        <div class="tag-btn-list">
          <div
            class="tag-btn-item"
            :class="{
              'tag-btn-item-active': (twoCateList[tagActiveIndex]?.id || null) === (cate.id || null)
            }"
            v-for="(cate, idx) in twoCateList"
            :key="cate.id || idx"
            @click="handleSelectTwoCate(idx, cate)"
          >
            {{ cate.name }}
          </div>
        </div>
        <div class="tag-paging-list-btn">
          <img
            class="left-btn"
            @click="twoCatePreviousPage"
            src="@/assets/images/home/page-left-icon.png"
            :style="{ cursor: twoCategoryPage === 1 ? 'not-allowed' : 'pointer' }"
            alt=""
          />
          <img
            class="right-btn"
            @click="twoCateNextPage"
            :style="{
              cursor: twoCategoryPage >= foodTwoCategoryLastPage ? 'not-allowed' : 'pointer'
            }"
            src="@/assets/images/home/page-right-icon.png"
            alt=""
          />
        </div>
      </div>
    </div>

    <div class="desktop-scroll-list">
      <div class="scroll-list-item-content" v-if="!showNoData" v-loading="listLoading">
        <div class="scroll-list-item" v-for="food in list" :key="food.id" @click="handlePick(food)">
          <img
            class="image"
            v-if="Array.isArray(food.images) && food.images.length"
            :src="food.images[0].file.preview_url"
          />
          <div class="not-good-image" v-else>
            <img class="image" src="@/assets/images/home/not-goodimage.png" />
          </div>
          <div class="desc-box">
            <el-tooltip class="item" effect="dark" :content="food.name" placement="top">
              <div class="name">{{ food.name }}</div>
            </el-tooltip>
            <div class="money" v-if="firstSku(food)">￥{{ firstSku(food).price }}/份</div>
            <div class="count" v-if="firstSku(food) && firstSku(food).num">
              剩余：{{ firstSku(food).num }}
            </div>
          </div>
          <div class="positon-soldOut-box" v-if="food.num === 0">
            <img class="image" src="@/assets/images/home/yishouqing-icon.png" />
          </div>
        </div>
      </div>
      <div class="no-data-box" v-else>
        <NotData desc="暂无菜品配菜数据" />
      </div>
    </div>

    <div class="desktop-actions-btn-box">
      <div class="count-desc">
        <span v-if="!showNoData">共{{ list.length }}项</span>
      </div>
      <div class="btn-list">
        <div class="btn-item" @click="emit('back')">返回</div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import NotData from '@/components/NotData/Index.vue'
import { foodExtraList, fetchfoodCategoryList } from '@/api/food'
import { useSelectedActions } from '@/views/Diancai/hooks/useSelectedActions'

interface Props {
  currentFoodData?: any
}
interface Emits {
  (e: 'back'): void
  (e: 'pick', payload: any): void
}

const props = withDefaults(defineProps<Props>(), { currentFoodData: null })
const emit = defineEmits<Emits>()

const list = ref<any[]>([])
const showNoData = ref(false)
const listLoading = ref(false)

const oneCateList = ref<any[]>([])
const twoCateList = ref<any[]>([])
const pagingActiveIndex = ref(0)
const tagActiveIndex = ref(-1)
// 分页控制（与 OrderDishMenu 对齐）
const foodOneCategoryLastPage = ref(1)
const foodTwoCategoryLastPage = ref(1)
const oneCategoryPage = ref(1)
const twoCategoryPage = ref(1)

const query = ref<{
  page: number
  limit: number
  category_id: number | null
  keywords: string | null
  food_id: any
}>({ page: 1, limit: 12, category_id: null, keywords: null, food_id: null })

watch(
  () => props.currentFoodData,
  val => {
    if (!val) return
    console.log(val)

    query.value.food_id = (val as any)?._raw?.id
    loadOneCate()
    loadList()
  },
  { immediate: true }
)

const firstSku = (food: any) => {
  return Array.isArray(food?.skuList) && food.skuList.length ? food.skuList[0] : null
}

async function loadList() {
  try {
    listLoading.value = true
    const res: any = await foodExtraList(query.value)
    if (res?.status === 200) {
      list.value = res.data?.data || []
      showNoData.value = (res.data?.total || 0) === 0 || list.value.length === 0
    }
  } catch (e) {
    showNoData.value = true
  } finally {
    listLoading.value = false
  }
}

async function loadOneCate() {
  try {
    // 一级分类：parent_id 为 0（第一页 limit 4，其余页 limit 5，与菜单保持一致）
    const res: any = await fetchfoodCategoryList({
      page: oneCategoryPage.value,
      limit: oneCategoryPage.value === 1 ? 4 : 5,
      parent_id: 0
    })
    const arr = Array.isArray(res?.data?.data) ? res.data.data.slice() : []
    oneCateList.value = oneCategoryPage.value === 1 ? [{ id: null, name: '全部' }, ...arr] : arr
    pagingActiveIndex.value = 0
    // 二级分类重置
    twoCateList.value = []
    tagActiveIndex.value = -1
    foodOneCategoryLastPage.value = Number(res?.data?.last_page || 1)
  } catch (e) {
    oneCateList.value = [{ id: null, name: '全部' }]
  }
}

const handleSelectOneCate = async (idx: number, item: any) => {
  pagingActiveIndex.value = idx
  query.value.category_id = item?.id || null
  // 拉取二级分类
  if (item?.id) {
    try {
      const res: any = await fetchfoodCategoryList({
        page: twoCategoryPage.value,
        limit: 5,
        parent_id: item.id
      })
      twoCateList.value = Array.isArray(res?.data?.data) ? res.data.data : []
      tagActiveIndex.value = -1
      foodTwoCategoryLastPage.value = Number(res?.data?.last_page || 1)
    } catch (e) {
      twoCateList.value = []
    }
  } else {
    twoCateList.value = []
    tagActiveIndex.value = -1
  }
  // 重置分页并刷新列表
  query.value.page = 1
  await loadList()
}

const handleSelectTwoCate = async (idx: number, item: any) => {
  tagActiveIndex.value = idx
  query.value.category_id = item?.id || null
  query.value.page = 1
  await loadList()
}

const onSearch = async () => {
  query.value.page = 1
  await loadList()
}

const handlePick = (food: any) => {
  if (food?.num === 0) {
    ElMessage.warning('该配菜已售罄')
    return
  }
  emit('pick', food)
}

// 一级分类上一页/下一页
const oneCatePreviousPage = async () => {
  if (oneCategoryPage.value === 1) return
  oneCategoryPage.value -= 1
  await loadOneCate()
}
const oneCateNextPage = async () => {
  if (oneCategoryPage.value >= foodOneCategoryLastPage.value) return
  oneCategoryPage.value += 1
  await loadOneCate()
}
// 二级分类上一页/下一页
const twoCatePreviousPage = async () => {
  if (twoCategoryPage.value === 1) return
  twoCategoryPage.value -= 1
  // 维持当前一级分类
  const one = oneCateList.value[pagingActiveIndex.value]
  if (one?.id) {
    await handleSelectOneCate(pagingActiveIndex.value, one)
  }
}
const twoCateNextPage = async () => {
  if (twoCategoryPage.value >= foodTwoCategoryLastPage.value) return
  twoCategoryPage.value += 1
  const one = oneCateList.value[pagingActiveIndex.value]
  if (one?.id) {
    await handleSelectOneCate(pagingActiveIndex.value, one)
  }
}
</script>

<style scoped lang="scss">
.desktop-content {
  box-sizing: border-box;
  width: 976px;
  height: 986px;
  background: #ffffff;
  border-radius: 20px;
  position: relative;
  .desktop-column-box {
    background: #ffffff;
    border-radius: 20px 20px 0px 0px;
    box-shadow: 0px 4px 6px 0px rgba(0, 0, 0, 0.04);
    padding: 20px 30px;
    .pagingAndSearch-box {
      display: flex;
      align-items: center;
      justify-content: space-between;
      .paging-list-box {
        position: relative;
        box-sizing: border-box;
        width: 700px;
        overflow: hidden;
        height: 48px;
        background: #ffffff;
        border: 1px solid #d0d0d0;
        border-radius: 25px;
        display: flex;
        align-items: center;
      }
      .paging-list-item {
        display: inline-block;
        padding: 0 24px;
        height: 48px;
        line-height: 48px;
        font-size: 16px;
        color: #333;
        cursor: pointer;
      }
      .paging-list-btn {
        position: absolute;
        top: 12px;
        right: 16px;
        display: flex;
        align-items: center;
      }
      .paging-list-btn .left-btn,
      .paging-list-btn .right-btn {
        flex-shrink: 0;
        width: 24px;
        height: 24px;
        cursor: pointer;
      }
      .paging-list-btn .left-btn {
        margin-right: 20px;
      }
      .paging-list-item .name {
        max-width: 80px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      .paging-list-item-active {
        color: #fff;
        background: #7c0a03;
        border-radius: 24px;
        .name {
          color: #fff !important;
        }
      }
      .search-box {
        display: flex;
        align-items: center;
        width: 192px;
        height: 48px;
        background: #d2d2d2;
        border-radius: 24px;
        box-sizing: border-box;
        .content1 {
          display: flex;
          align-items: center;
          padding-left: 22px;
          > img {
            flex-shrink: 0;
            width: 24px;
            height: 24px;
            margin-right: 20px;
          }
          > input {
            font-size: 16px;
            color: #333;
            border: none;
            outline: none;
            background: transparent;
          }
          > input::-webkit-input-placeholder {
            color: #fff;
          }
        }
      }
    }
    .tag-select-box {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-top: 20px;
    }
    .tag-btn-list {
      display: flex;
      align-items: center;
      max-width: 700px;
    }
    .tag-paging-list-btn {
      display: flex;
      align-items: center;
    }
    .tag-paging-list-btn .left-btn,
    .tag-paging-list-btn .right-btn {
      flex-shrink: 0;
      width: 24px;
      height: 24px;
      cursor: pointer;
    }
    .tag-paging-list-btn .left-btn {
      margin-right: 20px;
    }
    .tag-btn-item {
      min-width: 116px;
      height: 40px;
      line-height: 40px;
      border: 1px solid #d2d2d2;
      border-radius: 12px;
      font-size: 16px;
      text-align: center;
      color: #666;
      cursor: pointer;
      margin-right: 24px;
    }
    .tag-btn-item-active {
      border-color: #7c0a03 !important;
      color: #7c0a03 !important;
    }
  }
  .desktop-scroll-list {
    padding: 0 24px 24px 24px;
    height: 750px;
    box-sizing: border-box;
    overflow-y: auto;
    .scroll-list-item-content {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      justify-content: space-between;
      .scroll-list-item {
        position: relative;
        display: flex;
        align-items: flex-start;
        width: 300px;
        height: 130px;
        background: #f4f4f4;
        border-radius: 12px;
        box-sizing: border-box;
        margin-top: 20px;
        cursor: pointer;
        .image {
          flex-shrink: 0;
          width: 173px;
          height: 130px;
          border-radius: 12px 0 0 12px;
          margin-right: 10px;
        }
        .not-good-image {
          width: 173px;
          height: 130px;
          border-radius: 12px 0 0 12px;
          margin-right: 10px;
          display: flex;
          align-items: center;
          justify-content: center;
          .image {
            flex-shrink: 0;
            width: 124px;
            height: 124px;
          }
        }
        .desc-box {
          padding-top: 12px;
          .name {
            width: 90px;
            text-overflow: ellipsis;
            white-space: nowrap;
            overflow: hidden;
            font-size: 18px;
            font-weight: 700;
            color: #30314a;
          }
          .money {
            font-size: 14px;
            font-weight: 700;
            color: #333333;
            margin-top: 10px;
          }
          .count {
            font-size: 14px;
            font-weight: 400;
            color: #333333;
            margin-top: 30px;
          }
        }
      }
    }
    .positon-soldOut-box {
      position: absolute;
      left: 0;
      top: 0;
      width: 300px;
      height: 130px;
      background: rgba(0, 0, 0, 0.5);
      border-radius: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      .image {
        flex-shrink: 0;
        width: 142px;
        height: 117px;
      }
    }
  }
  .desktop-actions-btn-box {
    position: absolute;
    bottom: 0;
    left: 0;
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 970px;
    height: 88px;
    box-sizing: border-box;
    padding: 0 30px;
    background: #ffffff;
    box-shadow: 0px -4px 6px 0px rgba(0, 0, 0, 0.04);
    border-radius: 0px 0px 20px 20px;
    .count-desc {
      font-size: 14px;
      font-weight: 400;
      color: #30314a;
    }
    .btn-list {
      height: 88px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .btn-item {
        display: inline-block;
        padding: 0 42px;
        height: 48px;
        line-height: 48px;
        background: #ffffff;
        border: 1px solid #333333;
        border-radius: 12px;
        cursor: pointer;
        font-size: 18px;
        font-weight: 400;
        color: #333333;
        margin-right: 32px;
      }
      .btn-item:last-child {
        margin-right: 0;
      }
    }
  }
}
.no-data-box {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 170px;
  margin-top: 250px;
}
</style>
